package com.fbli.jedis;

import org.junit.Test;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class JedisDemo1 {
    public static void main(String[] args) {
        //创建Jedis对象
        Jedis jedis = new Jedis("192.168.25.128",6379);
        //测试连接
        String value = jedis.ping();
        System.out.println(value);
        //关闭连接
        jedis.close();
    }
    //操作key String
    @Test
    public void demo1(){
        //创建Jedis对象
        Jedis jedis = new Jedis("192.168.25.128",6379);
        //添加
        jedis.set("name","lucy");
        //获取
        String name = jedis.get("name");
        System.out.println(name);
        //设置多个key-value
        jedis.mset("k1","v1","k2","v2");
        List<String> mget = jedis.mget("k1", "k2");
        System.out.println(mget);
        Set<String> keys=jedis.keys("*");
        for (String key:keys){
            System.out.println(key);
        }
        //判断指定的key是否存在
        System.out.println(jedis.exists("k1"));
        //判断是否过期
        System.out.println(jedis.ttl("k1"));
        //获取key对应的值
        System.out.println(jedis.get("k1"));
        //关闭连接
        jedis.close();
    }
    //操作list
    @Test
    public void demo2(){
        //创建Jedis对象
        Jedis jedis = new Jedis("192.168.25.128",6379);
        //往左加
        jedis.lpush("key1","lucy","mary","jack");
        List<String> key1 = jedis.lrange("key1", 0, -1);
        System.out.println(key1);
        //关闭连接
        jedis.close();
    }
    //操作set
    @Test
    public void demo3(){
        //创建Jedis对象
        Jedis jedis = new Jedis("192.168.25.128",6379);
        jedis.sadd("names","lucy","jack");
        Set<String> name = jedis.smembers("names");
        System.out.println(name);
        //根据key删除
        jedis.srem("names","lucy");
        //关闭连接
        jedis.close();
    }
    //操作hash
    @Test
    public void demo4(){
        //创建Jedis对象
        Jedis jedis = new Jedis("192.168.25.128",6379);
        jedis.hset("users","age","23");
        String hget = jedis.hget("users", "age");
        System.out.println(hget);
        Map<String,String> map = new HashMap<String,String>();
        map.put("telphone","13810169999");
        map.put("address","atguigu");
        map.put("email","abc@163.com");
        jedis.hmset("hash2",map);
        List<String> result = jedis.hmget("hash2", "telphone","email");
        for (String element : result) {
            System.out.println(element);
        }
        //关闭连接
        jedis.close();
    }
    //操作zset
    @Test
    public void demo5(){
        //创建Jedis对象
        Jedis jedis = new Jedis("192.168.25.128",6379);
        jedis.zadd("china",100d,"shanghai");
        Set<String> china = jedis.zrange("china", 0, -1);
        System.out.println(china);
        //关闭连接
        jedis.close();
    }
}
